#include "Universe.h"
#include <QDir>
#include <QDateTime>
#include <QProcess>
#include "json/json.h"

Universe* Universe::mInstance=0;
Universe::Universe():QTcpServer()
{
   bool val= listen(QHostAddress(QString("127.0.0.1")),7777);

}
void Universe::Create()
{
    mInstance=new Universe();

}
void Universe::Free()
{
    delete mInstance;
    mInstance=0;
}
bool Universe::HasUser(const std::string& user)
{
    QString filename("key_");



    QString appPath=GetAppPath(false);
#ifdef WIN32
    QString msg("\\EchoServer\\");
 #else
    QString msg("/EchoServer/");
#endif

    QDir app(appPath+msg),dir(appPath);

    QDir appKey(appPath+msg+user.c_str()),appUser(appPath+msg);
    if(!appKey.exists())
        return false;
    return true;
}
QString Universe::GetAppPath(bool named)
{
#ifdef WIN32
    std::string apppathcode = "APPDATA=";
#else
    std::string apppathcode = "HOME=";
   #endif
    QStringList env=QProcess::systemEnvironment();
    QStringList::const_iterator constIterator;
       for (constIterator = env.constBegin(); constIterator != env.constEnd();++constIterator)
       {
           str data=(*constIterator).toLocal8Bit().constData();
           int c=data.find(apppathcode);
           if(c>=0)
           {
               data.replace(apppathcode.c_str(),"");
               if(named)
#ifdef WIN32
                data+="\\EchoServer\\";
 #else
                       data+="/EchoServer/";
#endif
               return data.c_str();
           }

       }
}
Universe::~Universe()
{

}
void Universe::SendNotif(QString type,QString sender,Json::Value& root)
{
    if(type=="authorizationAsk")
     {
        Json::Value notif(Json::objectValue);

        notif["jsonrpc"]="2.0";
        notif["method"]="message";
        notif["params"]["textEncrypted"]=root["params"]["textEncrypted"].asString();
        notif["params"]["counter"]="0";
        notif["params"]["messageId"]="messageId";
        notif["params"]["userId"]=sender.toStdString();
        notif["params"]["kind"]="AuthRequest";
        QDateTime mTime(QDateTime::currentDateTime());

        notif["params"]["date"]=mTime.toString("dd.MM.yyyy hh:mm:ss").toStdString();

        list<Dream*>::iterator it=mDreams.begin();
        while(it!=mDreams.end())
        {
            if((*it)->GetName().toStdString()==root["params"]["userId"].asString())
            {
                Json::FastWriter writer;
                (*it)->SendMessage(writer.write(notif));
            }
            it++;
        }
      }
    if(type=="authorizationConfirm")
     {
        Json::Value notif(Json::objectValue);

        notif["jsonrpc"]="2.0";
        notif["method"]="message";
        notif["params"]["textEncrypted"]=root["params"]["textEncrypted"].asString();
        notif["params"]["counter"]="0";
        notif["params"]["messageId"]="messageId";
        notif["params"]["userId"]=sender.toStdString();
        notif["params"]["kind"]="AuthConfirm";
        QDateTime mTime(QDateTime::currentDateTime());

        notif["params"]["date"]=mTime.toString("dd.MM.yyyy hh:mm:ss").toStdString();

        list<Dream*>::iterator it=mDreams.begin();
        while(it!=mDreams.end())
        {
            if((*it)->GetName().toStdString()==root["params"]["userId"].asString())
            {
                Json::FastWriter writer;
                (*it)->SendMessage(writer.write(notif));
            }
            it++;
        }
      }
    if(type=="message")
     {
        Json::Value notif(Json::objectValue);

        notif["jsonrpc"]="2.0";
        notif["method"]="message";
        notif["params"]["textEncrypted"]=root["params"]["textEncrypted"].asString();
        notif["params"]["counter"]=root["params"]["counter"];
        notif["params"]["messageId"]="messageId";
        notif["params"]["userId"]=sender.toStdString();
        notif["params"]["kind"]="message";
        QDateTime mTime(QDateTime::currentDateTime());

        notif["params"]["date"]=mTime.toString("dd.MM.yyyy hh:mm:ss").toStdString();

        str name=root["params"]["userId"].asString();
        list<Dream*>::iterator it=mDreams.begin();
        while(it!=mDreams.end())
        {
            if((*it)->GetName().toStdString()==name)
            {
                Json::FastWriter writer;
                (*it)->SendMessage(writer.write(notif));
            }
            it++;
        }
      }


}

void Universe::incomingConnection(qintptr handle)
{
    Dream* dream = new Dream(this,handle);
    mDreams.push_back(dream);
}


 void Universe::Check()
 {
     list<Dream*>::iterator it=mDreams.begin();
     while(it!=mDreams.end())
     {
         if(!(*it)->IsAlive())
         {
             delete *it;
             mDreams.erase(it);
             break;
         }
         it++;
     }
 }



